import {
	observable,
	action,
} from 'mobx';
import {
	WeaForm
} from 'comsMobx';

export default class FormStore {
	constructor(root) {
		this.root = root
	}

	@observable form = new WeaForm();
	@observable conditions = [];
	@observable loading = false;

	@observable searchGroupProps = {};
	@observable comProps = {};
	@observable customRenderKeyList = [];
	@observable linkageConfigs = [];
	@observable mark = '';
	@observable hasOrderNumber = false;
	@observable labelPres = {};

	get otherComponents() {
		const mark = (this.mark !== undefined) ? this.mark : '';
		return this.root[`${mark}OtherComponents`];
	}

	@action init = (config) => {
		Object.keys(config).forEach(key => {
			this[key] = config[key];
		})
	}

	@action fetchForm = (params = {}, exportDatas, afterInit) => {
		this.loading = true;
		this.form = new WeaForm();
		
		return this.api(params).then(datas => {
			exportDatas && exportDatas(datas);
			
			const conditions = this.getCondition(datas);

			if (this.isCustomRender) { 
				this.conditions = conditions;
				this.form.initFormFields(conditions, afterInit);
			} else {
				this.form.setCondition(conditions);
			}

			this.loading = false;

		})
	}

	validateForm = (form) => {
		return new Promise((resolve, reject) => {
			form.validateForm().then(f => {
				if (f.isValid) {
					resolve();
				} else {
					f.showErrors();
				}
			})
		})
	}

	collectViewAttr3keys = (conditions) => {
		let keys = [];
		this.conditions.forEach(c => {
			c.items.forEach(item => {
				const {
					viewAttr,
					domkey
				} = item;

				if (viewAttr === 3) {
					let key;
					if (domkey.length > 1) {
						key = domkey.join('__');
					} else {
						key = domkey[0];
					}
					keys.push(key);
				}
			})
		})
		return keys
	}

	collectHideFormFieldKeys = (showFormFieldKeys) => {
		const viewAttr3keys = this.collectViewAttr3keys();
		return viewAttr3keys.filter(key => !showFormFieldKeys.includes(key));
	}

	getCondition = (datas) => {
		let c = [];
		Object.keys(datas).forEach(key => {
			if (key.includes('condition')) {
				c = datas[key];
			}
		})
		return c;
	}

	handleFormChange = (datas) => {
		this.root.handleFormChange && this.root.handleFormChange(datas);
	}

	setCustomRenderKeyList = (customRenderKeyList) => {
		this.customRenderKeyList = customRenderKeyList;
	}

}